package com.ibpd.henuocms.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.MD5;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.common.des.DesUtil;
import com.ibpd.henuocms.common.des.ScoreUtil;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.UserEntity;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.service.user.IUserService;
import com.ibpd.henuocms.service.user.UserServiceImpl;
import com.ibpd.shopping.entity.TenantEntity;
import com.ibpd.shopping.service.userTenant.IUserTenantService;
import com.ibpd.shopping.service.userTenant.UserTenantServiceImpl;

@Controller
public class User extends BaseController {
	private ISubSiteService siteServ=null;
	private IUserTenantService utServ=null;
	IUserService userServ=null;

	@Resource(name="subSiteService")
	public void setSiteServ(ISubSiteService siteServ) {
		this.siteServ = siteServ;
	}
	@Resource(name="userTenantService")
	public void setUtServ(IUserTenantService utServ) {
		this.utServ = utServ;
	}
	@Resource(name="userService")
	public void setUserServ(IUserService userServ) {
		this.userServ = userServ;
	}
	
	@RequestMapping("Manage/login.do")
	public String login(Model model,HttpServletRequest req) throws IOException{
		model.addAttribute(PAGE_TITLE,"用户登录");
		String uuid=UUID.randomUUID().toString();
		SysUtil.setLoginDesKey(uuid,req);
		model.addAttribute("key",uuid);
		return "manage/login";
	}
	@RequestMapping("Manage/User/doLogin.do")
	public void doLogin(String userName,String password,String type,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		userName=(userName==null)?"":userName;
		password=(password==null)?"":password;
		userName=DesUtil.decrypt(userName,SysUtil.getLoginDesKey(req));
		password=DesUtil.decrypt(password,SysUtil.getLoginDesKey(req));
		type=(type==null)?"":type;
		if(StringUtil.isBlank(userName)){
			super.printMsg(resp, "-1", "-1", "用户名不能为空");
			return;
		}
		if(StringUtil.isBlank(password)){
			super.printMsg(resp, "-2", "-1", "密码不能为空");
			return;
		}
		if(StringUtil.isBlank(type)){
			super.printMsg(resp, "-3", "-1", "登录类别为空");
			return;
		}
		String sname=IbpdCommon.getInterface().getPropertiesValue("superManagerName");
		String spsd=IbpdCommon.getInterface().getPropertiesValue("superManagerPassword");
		if(sname.equals(userName) && spsd.equals(password)){
			SysUtil.setCurrentLoginedUserType(req.getSession(), "supermanager");
			UserEntity u=new UserEntity();
			u.setUserName(sname);
			u.setTrueName("超级管理员");
			SysUtil.setCurrentLoginedUserInfo(req.getSession(), u);
			super.printMsg(resp, "99", "99", "以超级管理者身份登陆成功");
			return;	
		}
		UserEntity ue=userServ.getUserByUserName(userName);
		if(ue==null){
			super.printMsg(resp, "-4", "-1", "没有该用户");
			return;
		}
		if(!ue.getState().equals(UserEntity.USER_STATE_PASS)){
			super.printMsg(resp, "-6", "-1", "用户尚未审核");
			return;						
		}
		//user is exists
		String newpsd=MD5.md5(password);
		if(!ue.getPassword().equals(newpsd)){
			super.printMsg(resp, "-5", "-1", "密码错误");
			return;			
		}
		SysUtil.setCurrentLoginedUserInfo(req.getSession(), ue);
		SysUtil.initUserAllPermission(req.getSession());
		if(ue.getSubSiteId()!=null){
			SubSiteEntity site=siteServ.getEntityById(ue.getSubSiteId());
			if(site!=null){
				SysUtil.setCurrentLoginedSiteInfo(req.getSession(), site);
			}
		}
		if(type.toLowerCase().trim().equals("manage")){
			
			if(utServ.checkUserTenantContrast(ue.getId())){
				super.printMsg(resp, "-6", "-1", "该用户为[商户管理员],请选择登录类别为[商户]");
				return;							
			}
			SysUtil.setCurrentLoginedUserType(req.getSession(), "manage");
			TenantEntity tenant=new TenantEntity();
			tenant.setId(-1L);
			tenant.setEntFullName("总部平台");
			SysUtil.setCurrentLoginedUserTenant(req.getSession(), tenant);
			super.printMsg(resp, "99", "99", "以管理者身份登陆成功");
			return;	
		}else if(type.toLowerCase().trim().equals("tenant")){
		
			if(!utServ.checkUserTenantContrast(ue.getId())){
				super.printMsg(resp, "-6", "-1", "该用户为[管理员],请选择登录类别为[管理员]");
				return;							
			}
			//设置登录的商户信息
			List<TenantEntity> tList=utServ.getUserTenantContrast(ue.getId());
			if(tList==null || tList.size()==0){
				super.printMsg(resp, "-7", "-1", "未找到对应的商户或商户未审核");
				return;							
				
			}
			SysUtil.setCurrentLoginedUserTenant(req.getSession(), tList.get(0));
			SysUtil.setCurrentLoginedUserType(req.getSession(), "tenant");
			super.printMsg(resp, "99", "99", "以商户身份登陆成功");
			return;	
		}
	}
	@RequestMapping("Manage/User/toEditCurrentUserPassword.do")
	public String toEditCurrentUserPassword(HttpServletRequest req,HttpServletResponse resp,Model model){
		UserEntity u=SysUtil.getCurrentLoginedUserInfo(req.getSession());
		if(u==null){
			model.addAttribute(ERROR_MSG,"尚未登录或登录已经失效");
			return ERROR_PAGE;
		}
		return "manage/user/editCurrentUserPassword";
	}
	@RequestMapping("Manage/User/doEditCurrentUserPassword.do")
	public void doEditCurrentUserPassword(HttpServletRequest req,HttpServletResponse resp,String psd) throws IOException{
		psd=(psd==null)?"":psd;
		if(StringUtil.isBlank(psd)){
			super.printMsg(resp, "-3", "-3", "密码不能为空");
			return;
		}
		UserEntity u=SysUtil.getCurrentLoginedUserInfo(req.getSession());
		if(u==null){
			super.printMsg(resp, "-1", "-1", "尚未登录或登录已经失效");
			return;
		}
		
		UserEntity ue=userServ.getEntityById(u.getId());
		if(ue==null){
			super.printMsg(resp, "-2", "-1", "未找到该用户");
			return;			
		}
		if(ue.getUserName().toLowerCase().trim().equals("superadmin")){
			super.printMsg(resp, "-2", "-2", "superadmin不允许");
			return;
		}
		ue.setPassword(MD5.md5(psd));
		userServ.saveEntity(ue);
		printDefaultSuccessMsg(resp);
	}
	@RequestMapping("Manage/User/doLogout.do")
	public void doLogout(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		SysUtil.removeCurrentLoginedUserInfo(req.getSession());
		SysUtil.removeCurrentLoginedUserType(req.getSession());
		SysUtil.removeCurrentTenant(req.getSession());
		SysUtil.clearUserPermission(req.getSession());
		super.printMsg(resp, "0", "0", "注销成功");
	}
	@RequestMapping("Manage/User/index.do")
	public String index(Model model,HttpServletRequest req) throws IOException{
		model.addAttribute(PAGE_TITLE,"用户管理");
		return "manage/user/index";
	}
	@RequestMapping("Manage/User/toChangePassword.do")
	public String toChangePassword(String ids,Model model,HttpServletResponse resp,HttpServletRequest req){
		model.addAttribute(PAGE_TITLE,"修改密码");
		model.addAttribute("ids",ids);
		return "manage/user/editPassword";
	}
	@RequestMapping("Manage/User/doChangePassword.do")
	public void toChangePassword(String ids,String password,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		
		if(ids==null){
			printParamErrorMsg(resp);
			return;
		}
		String[] idarr=ids.split(",");
		for(String id:idarr){
			UserEntity acc=userServ.getEntityById(Long.valueOf(id));
			if(acc!=null){
				if(!acc.getUserName().toLowerCase().trim().equals("superadmin")){
					acc.setPassword(MD5.md5(password));
					userServ.saveEntity(acc);
				}
			}
		}
		printDefaultSuccessMsg(resp);
	}
	@RequestMapping("Manage/User/doPass.do")
	public void doPass(String ids,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		
		if(ids==null){
			printParamErrorMsg(resp);
			return;
		}
		String[] idarr=ids.split(",");
		for(String id:idarr){
			UserEntity acc=userServ.getEntityById(Long.valueOf(id));
			if(acc!=null){
				if(acc.getUserName().toLowerCase().trim().equals("superadmin")){
					super.printMsg(resp, "-2", "-2", "superadmin不允许审核");
					return;
				}
				if(acc.getState().equals(UserEntity.USER_STATE_NOPASS)){
					acc.setState(UserEntity.USER_STATE_PASS);
				}else{
					acc.setState(UserEntity.USER_STATE_NOPASS);
				}
				userServ.saveEntity(acc);
			}
		}
		printDefaultSuccessMsg(resp);
	}
	@RequestMapping("Manage/User/list.do")
	public void list(HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryString,HttpServletRequest req) throws IOException{
		
		String query="";
//		userServ.getDao().clearCache();
		super.getList(req, userServ, resp, order, page, rows, sort, query);
	}
	@RequestMapping("Manage/User/props.do")
	public String props(Long id,Model model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null || id<0L){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
	
		UserEntity ce=userServ.getEntityById(id);
		if(ce==null){
			model.addAttribute(ERROR_MSG,"没有该类别");
			return super.ERROR_PAGE;
		}
		model.addAttribute(PAGE_TITLE,"参数设置");
		model.addAttribute("htmls",super.getHtmlString(ce, "user.edit.field"));
		model.addAttribute("entity",ce);
		return "manage/user/props";
	}	
	@RequestMapping("Manage/User/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
		
			UserEntity cata=userServ.getEntityById(id);
				if(cata!=null){
					//先确定参数类型
					Method tmpMethod=cata.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=cata.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					String uname=cata.getUserName();
					method.invoke(cata, val);
					cata.setUserName(uname);
					userServ.saveEntity(cata);
					super.printMsg(resp, "99", cata.getId().toString(), "保存成功");		
				}else{
					super.printMsg(resp, "-1", "", "没有该类别");
				}
		}else{
			printParamErrorMsg(resp);			
		}
	}
	@RequestMapping("Manage/User/toAdd.do")
	public String toAdd(Model model,HttpServletResponse resp,HttpServletRequest req) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{

		model.addAttribute(PAGE_TITLE,"添加");
		model.addAttribute("htmls",super.getHtmlString(null, "user.add.field"));
		
		Long siteId=SysUtil.getCurrentSiteId(req.getSession());
		if(siteId.equals(-1L)){
			List l=siteServ.getList();
			model.addAttribute("subSiteList",l);	
		}else{
			SubSiteEntity site=siteServ.getEntityById(siteId);
			List l=new ArrayList();
			l.add(site);
			model.addAttribute("subSiteList",l);
		}
		return "manage/user/add";
	}
	@RequestMapping("Manage/User/toEdit.do")
	public String toEdit(Long id,Model model,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null){
			return this.ERROR_PAGE;
		}
		
		UserEntity cata=userServ.getEntityById(id);
		if(cata==null){
			model.addAttribute(ERROR_MSG,"没有该用户");
			return this.ERROR_PAGE;
		}
		model.addAttribute(PAGE_TITLE,"编辑");
		model.addAttribute("htmls",super.getHtmlString(cata, "user.edit.field"));
		model.addAttribute("entity",cata);
		return "manage/user/edit";
	} 
	@RequestMapping("Manage/User/doEdit.do")
	public void doEdit(UserEntity entity,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(entity!=null && entity.getId()!=null && entity.getId()!=-1L){
			
			
			UserEntity cata=userServ.getEntityById(entity.getId());
			if(cata==null){
				super.printMsg(resp, "-1", "", "没有用户");
				return;
			}else{
				String psd=cata.getPassword();
				swap(entity,cata);
				cata.setPassword(psd);
				userServ.saveEntity(cata);
				super.printMsg(resp, "99", cata.getId().toString(), "保存成功");
				return;
			}
		}else{
			printParamErrorMsg(resp);
			return;
		}
		
	}
	@RequestMapping("Manage/User/doAdd.do")
	public void doAdd(UserEntity entity,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		
		
	
//		if(tenantServ.checkUserExist(entity.getUserName())){
//			super.printMsg(resp, "-1", "-1", "该会员名已经存在");
//			return;
//		}
		entity.setPassword(MD5.md5(entity.getPassword()));
		if(userServ.checkUserExist(entity.getUserName())){
			super.printMsg(resp, "-1", "-1", entity.getUserName()+"已存在");
		}
//		entity.setSubSiteId(SysUtil.getCurrentSiteId(req.getSession()));
		userServ.saveEntity(entity);	
		super.printMsg(resp, "99", "-1", "保存成功");
		 
	}
	@RequestMapping("Manage/User/doDel.do")
	public void doDel(String ids,HttpServletResponse resp) throws IOException{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		
		userServ.batchDel(ids);
		super.printMsg(resp, "99", "", "操作成功");	
	}

}
